﻿using Common;
using enterprise.Website.Core.Filter;
using FreeSql.Context;
using FreeSql.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace enterprise.Website.Core.ApiControllers
{
    [Route("api/[controller]")]
    [ApiController]
    [LoginAuthorize]
    public class FriendLinkController : ControllerBase
    {
        private readonly SqlContext _sqlContext;
        private readonly ICache _cache;
        private readonly IWebHostEnvironment _hostingEnvironment;
        public FriendLinkController(SqlContext sqlContext, IWebHostEnvironment hostingEnvironment, ICache cache)
        {
            _sqlContext = sqlContext;
            _hostingEnvironment = hostingEnvironment;
            _cache = cache;
        }

        /// <summary>
        /// 获取友情链接列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageModel<FriendLink>> Get(int page = 1,int limit = 10)
        {
            long Count = 0;
            var list = await _sqlContext.DB.Select<FriendLink, LanguageType>()
                .LeftJoin((t, t1) => t.LanguageId == t1.Id)
                .Page(page, limit)
                .Count(out Count)
                .OrderByDescending((t, t1) => t.Sort)
                .ToListAsync((t, t1) => new FriendLink
                {
                    Id = t.Id,
                    Title=t.Title,
                    LinkUrl=t.LinkUrl,
                    img=t.img,
                    LanguageId=t.LanguageId,
                    LanguageName=t1.Language,
                    CreateTime=t.CreateTime,
                    Sort=t.Sort
                });
            //计算总页数
            int pageCount = (Math.Ceiling(Count.ObjToDecimal() / limit.ObjToDecimal())).ObjToInt();
            return new PageModel<FriendLink>
            {
                count = Count,
                data = list,
                PageSize = limit,
                PageCount = pageCount,
                PageIndex = page,
                code = Count == 0 ? -1 : 0,
                msg = Count == 0 ? "暂无数据" : ""
            };
        }

        /// <summary>
        /// 新增友情链接
        /// </summary>
        /// <param name="value"></param>
        [HttpPost]
        public async Task<ApiResult> Post([FromBody] FriendLink data)
        {
            var result = new ApiResult { Success = false, Message = "保存失败" };
            if (data != null)
            {
                var Id= await _sqlContext.AddAsync(data);
                if (Id > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove($"{SystemConstConfig.FriendLinkKey}_{data.LanguageId}");
                }
            }
            return result;
        }

        /// <summary>
        /// 修改友情链接
        /// </summary>
        /// <param name="id"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ApiResult> Put(int id = 0, [FromBody]FriendLink data = null)
        {
            var result = new ApiResult { Success = false, Message = "保存失败" };
            if (id > 0 &&data != null)
            {
                data.Id = id;
                var Count = await _sqlContext.UpdateAsync(data);
                if (Count > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove($"{SystemConstConfig.FriendLinkKey}_{data.LanguageId}");
                }
            }
            return result;
        }

        /// <summary>
        /// 删除友情链接
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ApiResult> Delete(int id = 0)
        {
            var result = new ApiResult { Success = false, Message = "删除失败" };
            if (id > 0)
            {
                var FriendLinkInfo = await _sqlContext.QueryInfoAsync<FriendLink>(m => m.Id == id);
                if (FriendLinkInfo != null)
                {
                    var Count = await _sqlContext.DeleteAsync<FriendLink>(m => m.Id == id);
                    if (Count > 0)
                    {
                        result.Success = true;
                        result.Message = "删除成功";
                        //如果有图标，则删除对应的图标
                        if (!FriendLinkInfo.img.IsNullOrWhiteSpace())
                        {
                            string filePath = _hostingEnvironment.WebRootPath + FriendLinkInfo.img;
                            if (System.IO.File.Exists(filePath))//如果存在此文件，将其删除
                            {
                                System.IO.File.Delete(filePath);
                            }
                        }
                        _cache.Remove($"{SystemConstConfig.FriendLinkKey}_{FriendLinkInfo.LanguageId}");
                    }
                }
            }
            return result;
        }
    }
}
